package com.ddmmo.exhibition.localBOSS.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddmmo.exhibition.common.entity.Result;
import com.ddmmo.exhibition.common.enums.ResponseCodeEnum;
import com.ddmmo.exhibition.constant.SystemConstant;
import com.ddmmo.exhibition.localBOSS.project.entity.po.TbProjectClassifyPO;
import com.ddmmo.exhibition.localBOSS.project.entity.vo.ProjectClassifyListVO;
import com.ddmmo.exhibition.localBOSS.project.mapper.TbProjectClassifyMapper;
import com.ddmmo.exhibition.localBOSS.project.service.ProjectClassifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 后台管理-所属分类 - ServiceImpl
 * </p>
 *
 * @author JiangYiji
 * @since 2024/10/30
 */
@Slf4j
@Service
public class ProjectClassifyServiceImpl extends ServiceImpl<TbProjectClassifyMapper, TbProjectClassifyPO>  implements ProjectClassifyService {

    @Resource
    private TbProjectClassifyMapper tbProjectClassifyMapper;

    /*
     * 查询所有项目分类
     */
    @Override
    public List<ProjectClassifyListVO> selectAllProjectClassify() {
        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        List<TbProjectClassifyPO> tbProjectClassifyPOS = tbProjectClassifyMapper.selectList(queryWrapper);
        List<ProjectClassifyListVO> tree = buildTree(tbProjectClassifyPOS);
        return tree;
    }

    /*
     * 根据id查询项目分类
     */
    @Override
    public TbProjectClassifyPO selectProjectClassifyById(String id) {

        return tbProjectClassifyMapper.selectById(id);
    }

    /*
     * 添加项目分类
     */
    @Override
    public Result addProjectClassify(List<TbProjectClassifyPO> projectClassifys) {
        try {
            int successNum = 0;
            int failNum = 0;
            for (TbProjectClassifyPO projectClassify : projectClassifys){
                if (isClassifyNameExists(projectClassify.getClassifyName())) {
                    failNum++;
                    continue;
                }
                projectClassify.setId(UUID.randomUUID().toString().replaceAll("-", ""));

                // 父类ID为null默认最大类
                if (projectClassify.getParentId() == null) {
                    projectClassify.setParentId("0");
                }
                if (projectClassify.getClassifyNumber() == null) {
                    projectClassify.setClassifyNumber("0");
                }
                projectClassify.setDelFlag(SystemConstant.NO_DELETE);
                projectClassify.setCreateTime(new Date());
                projectClassify.setCreateBy(SystemConstant.USER);
                projectClassify.setUpdateTime(new Date());
                projectClassify.setUpdateBy(SystemConstant.USER);

                boolean success = save(projectClassify);
                if (!success) {
                    failNum++;
                }else {
                    successNum++;
                }
            }

            return Result.success("【添加项目分类】- 成功：" + successNum + "条，失败：" + failNum + "条");
        } catch (Exception e) {
            log.error("添加项目分类异常： {}" ,e);
            return Result.error(ResponseCodeEnum.ADD_ERROR);
        }
    }

    /*
     * 根据ID更新项目分类
     */
    @Override
    public Result updateProjectClassify(TbProjectClassifyPO projectClassify) {
        try {
            TbProjectClassifyPO existingClassify = getById(projectClassify.getId());
            if (existingClassify == null) {
                return Result.error(ResponseCodeEnum.NODATA);
            }
            existingClassify.setClassifyName(projectClassify.getClassifyName());
            existingClassify.setParentId(projectClassify.getParentId());
            existingClassify.setUpdateTime(new Date());
            existingClassify.setUpdateBy(SystemConstant.USER);

            boolean success = updateById(existingClassify);
            return success ? Result.success() : Result.error(ResponseCodeEnum.UPDATE_ERROR);

        } catch (Exception e) {
            log.error("根据ID更新项目分类： {}" ,e);
            return Result.error(ResponseCodeEnum.UPDATE_ERROR);
        }
    }

    /*
     * 根据id删除项目分类
     */
    @Override
    public Result deleteProjectClassifyById(String id) {
        try {
            boolean success = removeById(id);
            return success ? Result.success() : Result.error(ResponseCodeEnum.DELETE_ERROR);
        } catch (Exception e) {
            log.error("根据id删除项目分类异常： {}", e);
            return Result.error(ResponseCodeEnum.DELETE_ERROR);
        }
    }

    /*
     * 查询所有父类（不包括最小子类）
     */
    @Override
    public List<TbProjectClassifyPO> selectAllParentClassify() {
        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        queryWrapper.eq("parent_id", "0");
        List<TbProjectClassifyPO> parentClassifications = tbProjectClassifyMapper.selectList(queryWrapper);
//        List<ProjectClassifyListVO> tree = buildTree(parentClassifications);
        return parentClassifications;
    }

    /*
     * 查询所有子类（不包括最大父类）
     */
    @Override
    public List<TbProjectClassifyPO> selectAllChildClassify() {
        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        queryWrapper.ne("parent_id", "0");
        List<TbProjectClassifyPO> childClassifications = tbProjectClassifyMapper.selectList(queryWrapper);
//        List<TbProjectClassifyPO> tree = buildTree(childClassifications);
        return childClassifications;
    }

    /*
     * 根据父类id查询子类
     */
    @Override
    public List<TbProjectClassifyPO> selectChildByParentId(String id) {

        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        queryWrapper.eq("parent_id", id);
        List<TbProjectClassifyPO> childClassifications = tbProjectClassifyMapper.selectList(queryWrapper);
        return childClassifications;
    }

    /*
     * 根据名字或者ID查询子类（树形）
     */
    @Override
    public List<ProjectClassifyListVO> selectProjectClassifyByNameOrId(String name,String id) {

        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        if (name == null || name.equals("")){
            queryWrapper.eq("id", id);
        }else {
            queryWrapper.eq("classify_name", name);
        }
        queryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        TbProjectClassifyPO parentClassify  = tbProjectClassifyMapper.selectOne(queryWrapper);

        // 如果没有找到父分类，返回空列表
        if (parentClassify == null) {
            return Collections.emptyList();
        }

        String parentId = parentClassify.getId();
        QueryWrapper<TbProjectClassifyPO> childQueryWrapper = new QueryWrapper<>();
        childQueryWrapper.eq("parent_id", parentId);
        childQueryWrapper.eq("del_flag", SystemConstant.NO_DELETE);
        List<TbProjectClassifyPO> childClassifications = tbProjectClassifyMapper.selectList(childQueryWrapper);

        // 构建树形结构，包括父节点及其所有子节点
        childClassifications.add(parentClassify);
        List<ProjectClassifyListVO> tree = buildTreeByParentId(childClassifications,parentClassify.getId());
        return tree;
    }


    //辅助方法-查找孩子子类分类
    private List<ProjectClassifyListVO> buildTree(List<TbProjectClassifyPO> allClassifications) {

        Map<String, ProjectClassifyListVO> classifyMap = new HashMap<>();
        // 将所有分类放入 map 中，以便快速查找
        for (TbProjectClassifyPO classification : allClassifications) {
            ProjectClassifyListVO vo = new ProjectClassifyListVO();
            BeanUtils.copyProperties(classification, vo);
            vo.setClassifyId(classification.getId());
            classifyMap.put(vo.getClassifyId(), vo);
        }
        List<ProjectClassifyListVO> tree = new ArrayList<>();
        // 构建树形结构
        for (ProjectClassifyListVO vo : classifyMap.values()) {
            String parentId = vo.getParentId();
            if (parentId == null || parentId.equals("0")) {
                // 如果父节点为空或父节点为 "0"，则说明是根节点
                tree.add(vo);
            } else {
                // 否则，是子节点
                ProjectClassifyListVO parent = classifyMap.get(parentId);
                if (parent != null) {
                    // 如果父节点存在，加入父节点的子节点列表中
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    vo.setParentName(parent.getClassifyName());
                    parent.getChildren().add(vo);
                } else {     // 记录未找到的父节点
                   log.info("父节点不存在: " + vo.getClassifyId() + " 的父节点ID是: " + parentId);
                }
            }
        }
        return tree;
    }

    //辅助方法-查询分类名称是否存在
    private boolean isClassifyNameExists(String classifyName) {
        QueryWrapper<TbProjectClassifyPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classify_name", classifyName);
        return count(queryWrapper) > 0;
    }

    // 辅助方法-查找父类的子类（树结构）
    private List<ProjectClassifyListVO> buildTreeByParentId(List<TbProjectClassifyPO> allClassifications, String parentIdTree) {

        Map<String, ProjectClassifyListVO> classifyMap = new HashMap<>();

        // 分类放入 map
        for (TbProjectClassifyPO classification : allClassifications) {
            ProjectClassifyListVO vo = new ProjectClassifyListVO();
            BeanUtils.copyProperties(classification, vo);
            vo.setClassifyId(classification.getId());
            classifyMap.put(vo.getClassifyId(), vo);
        }

        List<ProjectClassifyListVO> tree = new ArrayList<>();

        // 构建树形结构
        for (ProjectClassifyListVO vo : classifyMap.values()) {
            String parentId = vo.getParentId();

            // 如果当前节点的父节点是传入的 parentIdTree，说明它是直接子节点
            if (!parentIdTree.equals(parentId)) {
                // 添加到树中
                tree.add(vo);
            } else {
                // 子节点
                ProjectClassifyListVO parent = classifyMap.get(parentId);
                if (parent != null) {
                    // 如果父节点存在，加入父节点的子节点列表中
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    vo.setParentName(parent.getClassifyName());
                    parent.getChildren().add(vo);
                } else {
                    // 记录未找到的父节点
                    log.error("父节点不存在: " + vo.getClassifyId() + " 的父节点ID是: " + parentId);
                }
            }
        }
        return tree;
    }

}
